﻿using Coldairarrow.IBusiness.Ocr;
using Coldairarrow.Util.ClassLibrary;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.Ocr
{
    [Route("/Ocr/[controller]/[action]")]
    
    public class Ocr_AnalysisController : BaseApiController
    {
        #region DI

        private readonly RedisOptions _redisOptions; 
        private readonly MongoDBOptions _mongodbOptions;
        // 百度云中开通对应服务应用的 API Key
        private readonly String clientId = "nc9Hc7uqoKhD3fUzcD3SGQDH";
        // 百度云中开通对应服务应用的 Secret Key
        private readonly String clientSecret = "AwS1uLVt3CLI3GruZMoayxzkl847mb3Q";

        public Ocr_AnalysisController(IOcr_AnalysisBusiness ocr_Analysis, IOptions<RedisOptions> redisOptions, IOptions<MongoDBOptions> mongodbOptions)
        {
            _ocr_Analysis = ocr_Analysis;
            _redisOptions = redisOptions.Value;
            _mongodbOptions = mongodbOptions.Value;
        }

        IOcr_AnalysisBusiness _ocr_Analysis { get; }

        #endregion

        #region 获取
        /// <summary>
        /// 获取车牌
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<IActionResult> GetLicensePlate()
        {
            var file = Request.Form.Files.FirstOrDefault();
            if (file == null)
                return JsonContent(new { Status = false,Msg="请先拍照" }.ToJson());
            string fileName = Guid.NewGuid().ToString("N");
            string path = $"/Upload/{fileName}/{file.FileName}";
            string physicPath = GetAbsolutePath($"~{path}");
            string dir = Path.GetDirectoryName(physicPath);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            using (FileStream fs = new FileStream(physicPath, FileMode.Create))
            {
                file.CopyTo(fs);
            }

            string url = $"{dir}/{file.FileName}";
            string plate = await _ocr_Analysis.GetLicensePlateAsync(clientId, clientSecret, url, _redisOptions);
           

            return JsonContent(new { Status = true, Msg = plate }.ToJson());
        }
        #endregion

    }
}
